<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import SlideVerify from '@/components/slide-verify.vue'
import { useMobileAuth, useSendSms, useUpdateMobile } from '@fl/api/mall-api'
import { SubmitBtn } from '@fl/components'
import { useAesEncrypt } from '@fl/hooks/web/useCrypt'
import { useUserStore } from '@fl/store/modules/user'
import { ElForm, ElFormItem } from 'element-plus'
import { computed, ref, unref } from 'vue'

const userStore = useUserStore()
const active = ref(0)
const isPwd = ref(false)
const verifyRef = ref()
const verifyRef1 = ref()

const step2FormRef = ref<FormInstance>()
const step1FormRef = ref<FormInstance>()

const { isPending: isPendingCode, mutate: mutateSendSms } = useSendSms()
const { mutate: mutateMobileAuth } = useMobileAuth()
const { isPending: isPendingStep2, mutate: mutateUpdateMobile } = useUpdateMobile()

type IForm = {
    code: string
    newMobile: string
}

const step1RuleForm = ref({
    code: '',
    currentMobile: userStore?.getUserInfo?.sysUser?.phonenumber,
    type: computed(() => (isPwd.value ? 1 : 2)),
})
const step2RuleForm = ref<IForm>({
    code: '',
    newMobile: '',
})

const step1Rules = reactive<FormRules>({
    code: [
        {
            // message: "请输入" + isPwd.value ? "密码" : "验证码",
            required: true,
            validator: (rule, value, callback) => {
                if (value.length === 0) {
                    callback(new Error(`请输入${isPwd.value ? '密码' : '验证码'}`))
                }
                else {
                    callback()
                }
            },
        },
    ],
})

const step2Rules = reactive<FormRules<IForm>>({
    code: [
        {
            message: '请输入验证码',
            required: true,
        },
    ],
    newMobile: [
        {
            message: '请输入手机号',
            required: true,
        },
        { message: '手机号码格式不正确', pattern: /^1[3-9]\d{9}$/, trigger: 'blur' },
    ],
})
const veryfyCodeFirstSending = ref(false)
const isVerify = ref(false)
const countdown = ref(0)
const verifyLabel = computed(() => {
    if (unref(veryfyCodeFirstSending)) {
        if (unref(countdown) > 0)
            return `${unref(countdown)}秒后重发`
        else return '重新发送'
    }
    else {
        return '发送验证码'
    }
})
// 发送验证码
async function sendVerifyCode() {
    if (active.value === 1) {
        const isValid = await unref(step2FormRef)!.validateField('newMobile')
        if (isValid) {
            // 如果已经是真实的人类, 允许提交表单
            if (verifyRef.value.isHuman)
                await verifySuccess()
            else isVerify.value = true
        }
    }
    else {
    // 如果已经是真实的人类, 允许提交表单
        if (verifyRef1.value.isHuman)
            await verifySuccess()
        else isVerify.value = true
    }
}

async function verifySuccess() {
    mutateSendSms(
        {
            mobile:
        active.value === 0
            ? String(step1RuleForm.value.currentMobile)
            : step2RuleForm.value.newMobile,
        },
        {
            onSuccess: () => {
                ElMessage.success('验证码已发送，请注意查收')
                //   发送验证码
                veryfyCodeFirstSending.value = true
                countdown.value = 60
                startCountdown()
                return true
            },
        },
    )
}

function startCountdown() {
    const interval = setInterval(() => {
        countdown.value = countdown.value - 1
        if (unref(countdown) === 0)
            clearInterval(interval)
    }, 1000)
}
const logoutCountDown = ref(3)

async function changeSteps(step) {
    if (step === 0) {
        active.value = 0
    }
    if (step === 1) {
        const isValid = await unref(step1FormRef)!.validate()
        if (!isValid) {
            return
        }
        // if (isPwd.value) {
        //     step1RuleForm.value.code = await useAesEncrypt(step1RuleForm.value.code)
        // }
        mutateMobileAuth({ ...step1RuleForm.value, code: isPwd.value ? await useAesEncrypt(step1RuleForm.value.code) : step1RuleForm.value.code }, {
            onSuccess: () => {
                ElMessage.success('验证成功')
                veryfyCodeFirstSending.value = false
                countdown.value = 0
                active.value = 1
            },
        })
    }
    if (step === 2) {
        const isValid = await unref(step2FormRef)!.validate()
        if (!isValid) {
            return
        }
        mutateUpdateMobile(step2RuleForm.value, {
            onSuccess: () => {
                ElMessage.success('修改手机号成功')
                veryfyCodeFirstSending.value = false
                countdown.value = 0
                active.value = 2
                const interval = setInterval(() => {
                    logoutCountDown.value = logoutCountDown.value - 1
                    if (unref(logoutCountDown) === 0) {
                        clearInterval(interval)
                        userStore.logoutConfirm()
                    }
                }, 1000)
            },
        })
    }
}
function changeVerifyType() {
    isPwd.value = !isPwd.value
    unref(step1FormRef)!.resetFields()
}
</script>

<template>
    <el-steps style="max-width: 100%"
              class="steps"
              align-center
              :active="active"
              finish-status="success"
    >
        <el-step title="身份验证" />

        <el-step title="修改手机号" />

        <el-step title="完成" />
    </el-steps>

    <div>
        <!-- step1 -->
        <div v-show="active === 0"
             style="margin: 0 auto; width: 400px"
        >
            <div class="mb-20 flex items-center">
                <div class="mr-30">
                    手机号：{{ userStore?.getUserInfo?.sysUser?.phonenumber }}
                </div>

                <div class="flex items-center">
                    {{ isPwd ? "忘记密码？" : "手机号不可用？" }}
                    <el-button text
                               type="primary"
                               style="color: #409eff"
                               @click="changeVerifyType"
                    >
                        {{ isPwd ? "使用验证码验证" : "使用密码验证" }}
                    </el-button>
                </div>
            </div>

            <ElForm ref="step1FormRef"
                    label-position="right"
                    :model="step1RuleForm"
                    :rules="step1Rules"
                    @submit.prevent
            >
                <ElFormItem :label="isPwd ? '密码' : '验证码'"
                            prop="code"
                >
                    <el-input v-model="step1RuleForm.code"
                              style="width: 200px"
                              :type="isPwd ? 'password' : 'text'"
                              minlength="6"
                              :maxlength="isPwd ? 20 : 6"
                              :show-password="isPwd"
                    />

                    <SubmitBtn v-if="!!!isPwd"
                               type="defautl"
                               class="ml-20 h-40 w-100"
                               :disabled="countdown > 0"
                               :loading="isPendingCode"
                               @click="sendVerifyCode"
                    >
                        {{ verifyLabel }}
                    </SubmitBtn>
                </ElFormItem>
            </ElForm>

            <SlideVerify ref="verifyRef"
                         v-model:visible="isVerify"
                         @success="verifySuccess"
            />

            <div class="text-center">
                <SubmitBtn type="primary"
                           @click="changeSteps(1)"
                >
                    确认
                </SubmitBtn>
            </div>
        </div>

        <!-- step2 -->
        <div v-show="active === 1"
             style="margin: 0 auto; width: 400px"
        >
            <ElForm ref="step2FormRef"
                    label-position="right"
                    :model="step2RuleForm"
                    :rules="step2Rules"
                    @submit.prevent
            >
                <div class="mb-20 flex items-center">
                    <ElFormItem label="手机号"
                                prop="newMobile"
                    >
                        <el-input v-model="step2RuleForm.newMobile"
                                  style="width: 200px"
                                  placeholder="请输入新手机号"
                        />
                    </ElFormItem>
                </div>

                <div class="mb-20 flex items-center">
                    <ElFormItem label="验证码"
                                prop="code"
                    >
                        <el-input v-model="step2RuleForm.code"
                                  style="width: 200px"
                                  minlength="6"
                                  maxlength="6"
                                  placeholder="请输入验证码"
                        />

                        <SubmitBtn type="defautl"
                                   class="ml-20 h-40 w-100"
                                   :disabled="countdown > 0"
                                   @click="sendVerifyCode"
                        >
                            {{ verifyLabel }}
                        </SubmitBtn>
                    </ElFormItem>
                </div>

                <div class="text-center">
                    <SubmitBtn type="primary"
                               :is-loading="isPendingStep2"
                               @click="changeSteps(2)"
                    >
                        确认
                    </SubmitBtn>
                </div>
                <!-- <el-button type="default" @click="changeSteps(0)">上一步</el-button> -->
            </ElForm>

            <SlideVerify ref="verifyRef1"
                         v-model:visible="isVerify"
                         @success="verifySuccess"
            />
        </div>

        <!-- step3 -->
        <div v-show="active === 2"
             style="margin: 0 auto; width: 600px"
             class="text-20 text-center"
        >
            手机号修改成功， {{ logoutCountDown }} 秒后登出系统，请重新登录
        </div>
    </div>
</template>

<style lang="less" scoped>
@publicColor: #e9534a;
@publicHeight: 35px;

.steps {
    width: 100%;
    margin: 20px auto 50px;
    height: @publicHeight;

    :deep(.el-step) {
        height: 100%;

        .el-step__line {
            background-color: rgba(0, 0, 0, 0.15);
            margin-right: 30px !important;
            margin-left: 105px !important;
            top: 50%;
            height: 1px;
        }

        .el-step__icon {
            width: @publicHeight;
            height: @publicHeight;
            font-size: 16px;
            border: 1px solid;

            .el-step__icon-inner {
                font-weight: unset !important;
            }
        }

        .el-step__head.is-process {
            color: @publicColor;
            border-color: @publicColor;
        }

        .el-step__head.is-success {
            color: @publicColor;
            border-color: @publicColor;
        }

        .is-process .el-step__icon.is-text {
            background: @publicColor;
            color: #fff;
        }

        .el-step__title.is-process {
            color: @publicColor;
        }

        .el-step__title.is-success {
            color: #565656;
        }

        .el-step__title {
            position: absolute;
            top: calc((100% - @publicHeight) / 2);
            left: calc(50% + 25px);
        }
    }
}
</style>
